import { Injectable } from '@nestjs/common';
import { CreateUserDto, LoginUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from 'src/schemas/user.schema';
import { PasswordEncryptionService } from 'src/service/password.service';
import { TokenService } from 'src/service/token.service';
import { CaptchaService } from 'src/service/captcha.service';
import { NestException } from 'src/exception/nest.exception';

@Injectable()
export class UserService {
  constructor(
    @InjectModel(User.name) private userModel: Model<User>,
    private readonly tokenService: TokenService,
    private readonly captchService: CaptchaService,
  ) {}

  async create(createUserDto: CreateUserDto) {
    const createUser = new this.userModel(createUserDto);
    return createUser.save();
  }

  async findAll() {
    const res = await this.userModel.find();
    return res;
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
  // 获取图形验证码
  getCode() {
    const captcha = this.captchService.generateCaptcha();
    return captcha;
  }
  async login(createUserDto: LoginUserDto, captcha: string | undefined) {
    // if (!captcha) {
    //   throw new NestException('验证码过期');
    // }
    // if (captcha !== createUserDto.code) {
    //   throw new NestException('验证码错误');
    // }
    // 查找用户
    const { userName, password } = createUserDto;
    const user = await this.userModel.findOne({ userName });
    if (user) {
      // 判断密码
      const flag = await PasswordEncryptionService.comparePassword(
        password,
        user.password,
      );
      if (flag) {
        // 签发token
        const token = this.tokenService.sign({ userName, role: user.role });
        return { token };
      } else {
        throw new NestException({ code: 1, message: '密码错误' });
      }
    }
    throw new NestException({ code: 1000, message: '用户未找到' });
  }
}
